// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;

namespace SnapObjects.Data.PostgreSql
{
    internal class PostgreSqlSqlSelectStatementGenerator : SqlSelectStatementGenerator
    {
        public PostgreSqlSqlSelectStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {

        }

        protected override IReadOnlyList<SqlToken> SpliceStatement(SqlStatement statement)
        {
            var result = new List<SqlToken>();

            var select = (SqlSelectStatement)statement;

            this.CreateSelectKeyword(result, select);
            this.CreateSelectColumns(result, select);
            this.CreateFrom(result, select);
            this.CreateWhere(result, select);
            this.CreateGroupBy(result, select);
            this.CreateHaving(result, select);
            this.CreateUnions(result, select);
            this.CreateOrderBy(result, select);
            this.CreateLimitKeyword(result, select);

            return result;
        }

        protected override void CreateSelectKeyword(List<SqlToken> tokens, SqlSelectStatement select)
        {
            tokens.Add(new SqlKeywordToken(SqlKeywords.SELECT));

            if (select.IsDistinst)
            {
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlKeywordToken(SqlKeywords.DISTINCT));
            }

            tokens.Add(SqlWhitespaceToken.Whitespace);
        }

        private void CreateLimitKeyword(List<SqlToken> tokens, SqlSelectStatement select)
        {
            if (select.Take > -1)
            {
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlKeywordToken(PostgreSqlSqlKeywords.LIMIT));
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlNumericToken(select.Take.ToString()));
                tokens.Add(SqlWhitespaceToken.Whitespace);
            }

            if (select.Skip > -1)
            {
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlKeywordToken(PostgreSqlSqlKeywords.OFFSET));
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlNumericToken(select.Skip.ToString()));
                tokens.Add(SqlWhitespaceToken.Whitespace);
            }
        }
    }
}
